﻿using LS.Infrastructure.ControllerExtension;
using LS.Infrastructure.UtilsExtension;
using Microsoft.AspNetCore.Mvc;
using QInfrastructure.Interfaces;
using QInfrastructure.Models;
using QInfrastructure.Models.SystemManager;
using System.Security.Claims;

namespace QInfrastructure.WebCore;

#nullable disable
public class QBaseController:LSBasicController
{
    public SystemUser CurrentUser { get; set; }

    protected new T GetService<T>() where T : TService
    {
        //获取用户信息

        var service= base.HttpContext.RequestServices.GetService<T>();
        if (HttpContext.User.HasClaim(x => x.Type == ClaimTypes.NameIdentifier))
        {
            var userId = HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);
            if (userId != null && userId.Value.IsNot_NullOrWhiteSpace())
            {
                var LoginUserId = Guid.Parse(userId.Value);
                var users = QInfrastructureCache.GetQCache<SystemUser>();
                if (users.Count > 0)
                {
                    var tmpuser= users.FirstOrDefault(x => x.Id == LoginUserId);
                    if(tmpuser != null)
                    {
                        tmpuser.UserPwd = "";
                        CurrentUser = tmpuser;
                        service.CurrentUser= CurrentUser;
                    }
                }
            }
        }
            
       
        return service;
    }


    protected IActionResult QBaseModelEdit<PK, T>(PK Id, Func<PK, T> func, Action<T>? action = default) where T :class , new()
    {
        T model = func?.Invoke(Id) ?? new T();
        action?.Invoke(model);
       
        return View(model);

    }

}
